import { useEffect, useState, useRef, useMemo, useLayoutEffect } from 'react';
import { Modal, Button } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux';
import loadable from '@loadable/component';
import dayjs from 'dayjs';

import { GET_FILE_STREAM } from '@/config/url'
import { getKeyFromUrl } from '@/utils';

import styles from './index.module.scss';

const FuncContainer = loadable(() => import('./../FuncContainer'));

export default props => {
    const initState = () => ({
        loading: false,
    });
    const [state, setState] = useState(initState);
    const { open, dataSource={}, onCancel, onOk } = props;
    const { userInfo={} } = useSelector(s => s.common);

    // 下载海报
    const downloadPoster = () => {
        html2canvas(document.querySelector("#poster"), {
            scale: 2
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/png');
            const link = document.createElement('a');
            link.href = imgData;
            link.download = 'poster.png';
            link.click();
        });
    }

    // 初始化画布
    const initCanvas = async (id) => {
        // 生成二维码
        const url = `${location.origin}/?inviter=${userInfo.invitationCode}`;
        $('#qrcode').empty();
        let qrcode = new QRCode(document.getElementById("qrcode"), {
            text: url,
            width: 64,
            height: 64,
            colorDark : "#000000",
            colorLight : "#ffffff",
            correctLevel : QRCode.CorrectLevel.H,
        });
    };

    const joinTime = () => {
        const start = userInfo.createTime ? dayjs(userInfo.createTime) : dayjs();;
        return dayjs().diff(start, 'day');
    };

    const afterOpenChange = open => {
        if(open) {
            const id = getKeyFromUrl('id');
            initCanvas(id);
        }
    }

    const lastObj = useMemo(() => {
        const obj = (dataSource?.memberCourseHomeworkSubmitDetailList||[]).findLast(i => 4 === i.question?.type);

        return obj;
    }, [dataSource]);

    return (
        <Modal
            header={null}
            footer={null}
            maskClosable={false}
            closable={false}
            open={open}
            rootClassName={styles['modal-root']}
            width={360}
            afterOpenChange={afterOpenChange}
        >
            <FuncContainer className={styles['container']}>
                { state.loading ? <Loading/> : null }
                <Button className={styles['close']} type="text" size="small" icon={<CloseOutlined/>} onClick={onCancel}></Button>
                <div className={styles['container-box']} id="poster">
                    <div className={styles['logo']}><img src="/images/logo.png"/></div>
                    <div className={styles['info']}>
                        <div className={styles['avatar']}><img src={userInfo.avatar ? `${GET_FILE_STREAM}?url=${userInfo.avatar}` : '/images/logo.png'} /></div>
                        <div className={styles['text']}>
                            <div className={styles['name']}>{userInfo.nickName||'--'}</div>
                            <div className={styles['time']}>加入易容{joinTime()}天</div>
                        </div>
                    </div>
                    <div className={styles['title']}>{dataSource?.courseTitle||'--'}</div>
                    <div className={styles['summary']}>{lastObj?.question?.name || '--'}</div>
                    <div className={styles['content']}>{dataSource?.previewAnswer || '--'}</div>

                    <div className={styles['footer']}>
                        <div className={styles['qrcode']}><div id="qrcode"></div></div>
                        <div className={styles['f']}>
                            <div>
                                <p>我在易容学打铁</p>
                                <p>不信看我七十二变</p>
                            </div>
                            <div>长按扫码，前来观战</div>
                        </div>
                    </div>
                </div>

                <div className={styles['download']}>
                    <Button type="primary" shape="round" onClick={downloadPoster}>下载图片</Button>
                </div>
            </FuncContainer>
        </Modal>
    );
}
